<template>
	<view>
		<topbar :backgroundColor="backgroundColor" :navButtonColor="navButtonColor"></topbar>

		<uni-grid :column="2" :showBorder="false" :square="false">
			<connectioncard v-for="(item, index) in connectionInfos" :key="index" :name="item.name" :ip="item.ip"
				:port="item.port" :imageUrl="item.cover" @click.native="toConnectionInfo(item.id, item.name, item.port, item.ip, item.cover)"></connectioncard>
		</uni-grid>
	</view>
</template>

<script>
	import connectioncard from '@/components/connectioncard/connectioncard.vue'
	import {
		allConnectionForIndex
	} from '@/api/database/index.js'
	export default {
		components: {
			connectioncard
		},
		data() {
			return {
				connectionInfos: [],
				backgroundColor: '',
				navButtonColor: '',
				page: 1,
				pageSize: 10
			}
		},
		onReady() {
			this.connectionInfos = []
			this.page = 1
			this.doAllConnectionForIndex()
			plus.screen.lockOrientation('portrait-primary');
		},
		onShow() {
			plus.screen.lockOrientation('portrait-primary');
			this.backgroundColor = uni.getStorageSync('backgroundColor') != '' ? uni.getStorageSync('backgroundColor') : '#162bed'
			this.navButtonColor = this.getDarkColor(this.backgroundColor, 0.2)
			uni.setStorageSync('navButtonColor', this.navButtonColor)
		},
		methods: {
			doAllConnectionForIndex() {
				allConnectionForIndex({
					page: this.page,
					pageSize: this.pageSize
				}).then((res) => {
					if (res == null) {
						return
					}
					
					this.connectionInfos = [...this.connectionInfos, ...res.data]
					this.page = this.page + 1
				})
			},
			toConnectionInfo(id, name, port, ip, cover) {
				uni.navigateTo({
					url: '/pages/database/mysql/connectionInfo?id=' + id + '&name=' + name + '&port=' + port + '&ip=' + ip + '&cover=' + cover
				})
			},
			getDarkColor(color, level) {
				var r = /^\#?[0-9A-F]{6}$/;
				var rgbc = this.HexToRgb(color);
				for (var i = 0; i < 3; i++) rgbc[i] = Math.floor(rgbc[i] * (1 - level));
				return this.RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
			},
			HexToRgb(str) {
				var r = /^\#?[0-9A-F]{6}$/;
				str = str.replace("#", "");
				var hxs = str.match(/../g);
				for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
				return hxs;
			},
			RgbToHex(a, b, c) {
				var r = /^\d{1,3}$/;
				var hexs = [a.toString(16), b.toString(16), c.toString(16)];
				for (var i = 0; i < 3; i++)
					if (hexs[i].length == 1) hexs[i] = "0" + hexs[i];
				return "#" + hexs.join("");
			}
		}
	}
</script>

<style>
</style>
